from django.shortcuts import render
from lms.models import User
from lms.models import Book
from lms.models import Borrow
from lms.models import Reader
import json
from django.views.decorators.csrf import csrf_exempt

# Create your views here.
def index(request):
    # 如果用户已经登录过，session中会有username，就直接登录首页，否则，需要登录。
    if request.session.get('username'):
        query_res = Book.objects.all()
        borrow = Borrow.objects.select_related('bookno','readerno').all()
        return render(request,"lms/index.html",{"res":query_res,'borrow': borrow})
    else:
        return render(request,"lms/login.html")


def login(request):
    # 获取用户通过表单post方式传过来的参数，括号中的参数是表单元素的name
    username = request.POST.get('username')
    password = request.POST.get('password')
    # 提前设置好提示语
    fail_user = "用户不存在！"
    fail_psw = "密码错误！"
    # 首先判断用户名是否存在，exist()返回值是True或False
    flag = User.objects.filter(user_name=username).exists()
    # 如果用户存在，就进一步判断对应的密码是否匹配
    if flag:
        # 查询数据库，获取这个用户的信息
        query_res = User.objects.get(user_name=username)
        # 判断用户的密码是否匹配，匹配的话，就跳转到首页
        if query_res.password == password:
            # 如果页面有其他数据要从数据库获取，那就获取他们，一起返回给前台模板
            query_res = Book.objects.all()
            borrow = Borrow.objects.all()
            request.session["username"] = username
            return render(request, 'lms/index.html',{'res': query_res,'borrow': borrow})
        # 如果密码不匹配，则在login页面显示“密码错误！”的提示信息
        else:
            return render(request, 'lms/login.html', {'fail_str': fail_psw})
    # 如果用户不存在，则在login页面显示“用户不存在！”的提示信息
    else:
        return render(request, 'lms/login.html', {'fail_str': fail_user})


def logout(request):
    if request.session.get("username"):
        del request.session["username"]
    return render(request, 'lms/login.html')


def imgSave(request):
    return render(request,'')


@csrf_exempt
def addbook(request):
    bookno = request.POST.get('bookno')
    bookname = request.POST.get('bookname')
    author = request.POST.get('author')
    publisher = request.POST.get('publisher')
    publishdate = request.POST.get('publishdate')
    b = Book(bookno=bookno,bookname=bookname,authorname=author,publisher=publisher,publishdate=publishdate)
    b.save()
    return render(request,'lms/index.html',{'status':'success'})


def login1(request):
    return render(request, 'lms/login1.html', {})


def login2(request):
    return render(request,'lms/login2.html')


def test(request):
    return render(request, 'lms/test.html')